const { Connection, Keypair, Transaction, sendAndConfirmTransaction, PublicKey } = require('@solana/web3.js');
const { 
  getAssociatedTokenAddress, 
  createAssociatedTokenAccountInstruction, 
  createTransferInstruction,
  getAccount
} = require('@solana/spl-token');
const fs = require('fs');
const path = require('path');

const DEVNET_RPC = 'https://api.devnet.solana.com';
const TOKEN_MINT = '4C5SJj6Gfd86jTS7PgtYmjGjGxrG9GAuLUmQ47vGnQPc';
const YOUR_ADDRESS = 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac';

// 测试地址 (刚生成的有2 SOL余额的地址)
const TEST_ADDRESS = '6XjguvTFi8nWhZEfmYYFYW53bUXPkdEcRJ9AemhA1vVR';

async function setupTradingAccounts() {
  console.log('🎯 设置交易账户...');
  
  const connection = new Connection(DEVNET_RPC, 'confirmed');
  const tokenMint = new PublicKey(TOKEN_MINT);
  
  // 加载您的钱包 (从测试钱包文件)
  let yourKeypair;
  try {
    const walletPath = path.join(__dirname, '..', 'test-wallet-1754098590485.json');
    const walletData = JSON.parse(fs.readFileSync(walletPath, 'utf8'));
    yourKeypair = Keypair.fromSecretKey(new Uint8Array(walletData.secretKey));
    console.log(`✅ 加载您的钱包: ${yourKeypair.publicKey.toString()}`);
  } catch (error) {
    console.log('❌ 加载钱包失败:', error.message);
    return;
  }
  
  // 从文件中找到有SOL余额的测试地址
  let testKeypair;
  try {
    const addressesPath = path.join(__dirname, 'test-addresses.json');
    const addresses = JSON.parse(fs.readFileSync(addressesPath, 'utf8'));
    
    // 找到有SOL余额的地址
    const validAddr = addresses.find(a => a.balance && a.balance > 0);
    
    if (validAddr) {
      testKeypair = Keypair.fromSecretKey(new Uint8Array(validAddr.secretKey));
      console.log(`✅ 找到测试地址: ${testKeypair.publicKey.toString()}`);
      console.log(`💰 SOL余额: ${validAddr.balance} SOL`);
    } else {
      console.log('❌ 未找到有SOL余额的测试地址');
      
      // 显示所有地址的状态
      console.log('\n📋 所有地址状态:');
      addresses.forEach((addr, index) => {
        console.log(`${index + 1}. ${addr.publicKey}: ${addr.balance || 0} SOL`);
      });
      return;
    }
  } catch (error) {
    console.log('❌ 加载测试地址失败:', error.message);
    return;
  }
  
  // 检查您的代币余额
  const yourTokenAccount = await getAssociatedTokenAddress(tokenMint, yourKeypair.publicKey);
  
  let yourTokenBalance = 0;
  try {
    const yourAccount = await getAccount(connection, yourTokenAccount);
    yourTokenBalance = Number(yourAccount.amount);
    console.log(`💎 您的代币余额: ${yourTokenBalance / Math.pow(10, 9)} 个代币`);
  } catch (error) {
    console.log('❌ 您的代币账户不存在或没有代币');
    console.log('💡 请先确保您的地址有代币，或者创建代币');
    return;
  }
  
  if (yourTokenBalance === 0) {
    console.log('❌ 您的代币余额为0，无法转移');
    return;
  }
  
  // 创建测试地址的代币账户并转移代币
  console.log('\n💸 向测试地址转移代币...');
  
  const testTokenAccount = await getAssociatedTokenAddress(tokenMint, testKeypair.publicKey);
  
  // 检查测试地址的代币账户是否存在
  let accountExists = false;
  try {
    await getAccount(connection, testTokenAccount);
    accountExists = true;
    console.log('💎 测试地址代币账户已存在');
  } catch {
    console.log('💎 测试地址代币账户不存在，将创建');
  }
  
  const transaction = new Transaction();
  
  // 如果需要，创建代币账户
  if (!accountExists) {
    transaction.add(
      createAssociatedTokenAccountInstruction(
        yourKeypair.publicKey, // payer
        testTokenAccount,      // ata
        testKeypair.publicKey, // owner
        tokenMint             // mint
      )
    );
  }
  
  // 转移10,000个代币给测试地址
  const transferAmount = BigInt(10000 * Math.pow(10, 9));
  transaction.add(
    createTransferInstruction(
      yourTokenAccount,     // source
      testTokenAccount,     // destination
      yourKeypair.publicKey, // owner
      transferAmount        // amount
    )
  );
  
  try {
    const signature = await sendAndConfirmTransaction(
      connection,
      transaction,
      [yourKeypair],
      { commitment: 'confirmed' }
    );
    
    console.log(`✅ 代币转移成功！交易签名: ${signature}`);
    console.log(`💎 转移了 10,000 个代币给测试地址`);
    
    // 生成买家钱包文件
    const buyerWalletData = {
      publicKey: testKeypair.publicKey.toString(),
      secretKey: Array.from(testKeypair.secretKey)
    };
    
    const buyerWalletPath = path.join(__dirname, '..', '..', 'frontend', 'buyer-wallet.json');
    fs.writeFileSync(buyerWalletPath, JSON.stringify(buyerWalletData, null, 2));
    
    console.log(`\n🔑 买家钱包已生成: ${buyerWalletPath}`);
    console.log(`📍 买家地址: ${testKeypair.publicKey.toString()}`);
    console.log(`💰 SOL余额: 5 SOL`);
    console.log(`🪙 代币余额: 10,000 个`);
    
    // 也生成一个卖家钱包 (使用您的地址)
    const sellerWalletData = {
      publicKey: yourKeypair.publicKey.toString(),
      secretKey: Array.from(yourKeypair.secretKey)
    };
    
    const sellerWalletPath = path.join(__dirname, '..', '..', 'frontend', 'seller-wallet.json');
    fs.writeFileSync(sellerWalletPath, JSON.stringify(sellerWalletData, null, 2));
    
    console.log(`🔑 卖家钱包已生成: ${sellerWalletPath}`);
    console.log(`📍 卖家地址: ${yourKeypair.publicKey.toString()}`);
    console.log(`🪙 剩余代币余额: ${(yourTokenBalance - 10000 * Math.pow(10, 9)) / Math.pow(10, 9)} 个`);
    
    console.log('\n🚀 现在可以运行真实交易测试:');
    console.log('cd ../../frontend && node scripts/real-trade-test.js --confirm');
    
  } catch (error) {
    console.log('❌ 转移代币失败:', error.message);
  }
}

setupTradingAccounts();
